"""PAMR Data Collector

.. helpdoc::
Collects data into a PAMR Data Signal.  This widget really just collects the data and doesn't actually process anything.  However, all PAMR widgets require this kind of signal so that the expression data, the genes, and the samples can be kept in the propper context.

"""


"""<widgetXML>
    <name>PAMR Data Collector</name>
    <icon></icon>
    <tags>
        <tag>PAMR</tag>
    </tags>
    <summary>Collects data into a PAMR Data signal.</summary>
    <author>
        <authorname>Red-R Core Development Team</authorname>
        <authorcontact>www.red-r.org</authorcontact>
    </author>
    </widgetXML>
"""

## pamr object generator.  This widget combines vectors of classifications, expression matricies, gene lists, and gene ID's into a list for making a pamr object.  

"""
<name>Make PAMR Container</name>
<author>Kyle R Covington kyle@red-r.org</author>
<tags>PAMR</tags>
"""
from OWRpy import * 
import OWGUI 
import redRGUI, signals
import libraries.pamr.signalClasses.RPAMRData as pamrd

class pamrData(OWRpy): 
    settingsList = []
    def __init__(self,**kwargs):
        OWRpy.__init__(self, **kwargs)
        self.require_librarys(["pamr"])
        self.setRvariableNames(["pamr.data"])
        self.outputText = ''
        self.expressionMatrix = None
        self.sampleGroups = None
        self.geneID = None
        self.geneName = None
        
        """.. rrsignals::"""
        self.inputs.addInput('id0', "Expression Matrix", signals.base.RDataFrame, self.processMatrix)
        
        """.. rrsignals::"""
        self.inputs.addInput('id1', "Sample Groups", signals.base.RVector, self.processGroups)
        
        """.. rrsignals::"""
        self.inputs.addInput('id2', "Gene ID", signals.base.RVector, self.processGeneID)
        
        """.. rrsignals::"""
        self.inputs.addInput('id3', "Gene Names", signals.base.RVector, self.processGeneName)
        
        """.. rrsignals::"""
        self.outputs.addOutput("PAMR Data", 'PAMR Data Collection',  signals.pamr.RPAMRData)
        
        self.textArea = redRGUI.base.textEdit(self.controlArea, label = "PAMR Data Container")
        redRGUI.base.button(self.bottomAreaRight, "Refresh", callback = self.makeSummary)
        self.commitButton = redRGUI.base.commitButton(self.bottomAreaRight, "Commit", callback = self.commitFunction)
        self.commitButton.setEnabled(False)
    def processMatrix(self, data):
        ## put the data in the container
        if data:
            self.expressionMatrix = str(data.getData())
            rownames = self.R('rownames('+self.expressionMatrix+')', wantType = 'list') # get the rownames from the matrix if they are there.
            if 'NULL' not in rownames:
                self.geneID = 'rownames('+self.expressionMatrix+')'
        else:
            self.expressionMatrix = None
        
        self.makeSummary()
        
    def processGroups(self, data):
        if data:
            self.sampleGroups = str(data.getData())
        else:
            self.sampleGroups = None
        
        self.makeSummary()
        
    def processGeneID(self, data):
        if data:
            self.geneID = str(data.getData())
            
        else:
            self.geneID = None
            
        self.makeSummary()
        
    def processGeneName(self, data):
        if data:
            self.geneName = str(data.getData())
            
        else:
            self.geneName = None
            
        self.makeSummary()

    def makeSummary(self):
        commitOK = 1
        ## get the data for the elements if they exist
        if self.expressionMatrix:
            
            emd = self.R('dim('+self.expressionMatrix+')')
        else: 
            
            emd = [0,0]
            
        if self.sampleGroups:
            
            sgl = self.R('length('+self.sampleGroups+')')
        else: 
            
            sgl = 0
        
        if self.geneID:
            
            gil = self.R('length('+self.geneID+')')
        else:
            
            gil = 0
            
        # make the table indicating if there is an error in the data
        t1 = '<table border="1" cellpadding="3">'
        t1 += '   <tr><td>Expression Matrix</td><td>'
        if self.expressionMatrix:
            t1 += 'Good'
        else:
            t1 += 'Fail'
            commitOK = 0
        t1 += '</td></tr>'
        
        t1 += '<tr><td>Sample Groups</td><td>'
        if self.sampleGroups and sgl == emd[1]:
            t1 += 'Good'
        else:
            t1 += 'Fail'
            commitOK = 0
        t1 += '</td></tr>'
        
        t1 += '<tr><td>Gene ID</td><td>'
        if self.geneID and gil == emd[0]:
            t1 += 'Good'
        else:
            t1 += 'Fail'
            commitOK = 0
        t1 += '</td></tr></table>'
        
        
        self.outputText = t1 + '</br>'
        self.textArea.setHtml(self.outputText)
        
        if commitOK: self.commitButton.setEnabled(True)
        else: self.commitButton.setEnabled(False)
        
    def commitFunction(self):
        ## package all of the data into a singal for PAMR
        if self.geneName:
            if self.R('length('+self.geneName+')') == self.R('length('+self.geneID+')'):
                gNames = self.geneName
                
        else:
            gNames = self.geneID
                
        self.R(self.Rvariables['pamr.data']+'<-list(x = as.matrix('+self.expressionMatrix+'), y = as.factor('+self.sampleGroups+'), geneid = '+self.geneID+', genenames = '+gNames+')')
        
        newData = signals.pamr.RPAMRData(self, data = self.Rvariables['pamr.data'])
        self.rSend("PAMR Data", newData)
        
    def getReportText(self, fileDir):
        text = 'This widget collects data into a container for use in PAMR analysis.\n\n'
        #text += unicode(self.outputText)
        return text